<template>
  <div class="about">
    <div class="cesium-container" id="cesiumContainer"></div>
  </div>
</template>

<script>
import pinggubianjieJson from "../utils/南湖区.json";
export default {
  components: {},
  mixins: [],
  props: {},
  data() {
    return {
      flyToEntity: null,
      viewer: null,
      pointInfo: [
        {
          id: "392f7fbb-ae25-4eef-ac43-58fd91148d1f",
          latitude: "30.69712",
          longitude: "121.04633",
          psName: "有限公司1",
        },
        {
          id: "0278a88c-b4f4-4d64-9ccb-65831b3fb19d",
          latitude: "30.56226",
          longitude: "120.78369",
          psName: "有限公司2",
        },
        {
          id: "248f6853-2ced-4aa6-b679-ea6422a5f3ac",
          latitude: "30.9729",
          longitude: "120.9787",
          psName: "有限公司3",
        },
        {
          id: "F8DADA95-A438-49E1-B263-63AE3BD7DAC4",
          latitude: "30.86215",
          longitude: "120.50079",
          psName: "有限公司4",
        },
        {
          id: "9402a911-78c5-466a-9162-d5b04d0e48f0",
          latitude: "30.55517",
          longitude: "120.39368",
          psName: "有限公司5",
        },
        {
          id: "EB392DD3-6998-437F-8DCB-F805AD4DB340",
          latitude: "30.735304",
          longitude: "120.854717",
          psName: "有限公司有限公司有限公司6j",
        },
      ],
    };
  },
  computed: {},
  watch: {},
  created() {},
  mounted() {
    this.getInit();
  },
  methods: {
    // cesium 加载点位
    addMarker() {
      let that = this;
      // const Cesium = this.cesium;
      // 清除上一次加载的点位
      that.viewer.entities.removeAll();
      // foreach循环加载点位
      that.pointInfo.forEach((pointObj) => {
        that.viewer.entities.add({
          name: pointObj.psName,
          code: pointObj.id,
          id: pointObj.id,
          position: Cesium.Cartesian3.fromDegrees(
            pointObj.longitude * 1,
            pointObj.latitude * 1
          ),
          // 点
          // point: {
          //   pixelSize: 5,
          //   color: Cesium.Color.RED,
          //   outlineColor: Cesium.Color.WHITE,
          //   outlineWidth: 2,
          // },
          label: {
            text: pointObj.psName,
            font: "16px", //字体样式
            style: Cesium.LabelStyle.FILL,
            fillColor: Cesium.Color.fromCssColorString("#fff"), //字体颜色
            backgroundColor: Cesium.Color.fromCssColorString("#000"), //背景颜色
            showBackground: true, //是否显示背景颜色
            outlineWidth: 4,
            verticalOrigin: Cesium.VerticalOrigin.CENTER, // 垂直方向以底部来计算标签的位置
            horizontalOrigin: Cesium.HorizontalOrigin.CENTER, //水平位置
            pixelOffset: new Cesium.Cartesian2(0, -90), // 偏移量
          },
          // 图标
          billboard: {
            image: require("@/assets/zhong.png"),
            horizontalOrigin: Cesium.HorizontalOrigin.CENTER,
            verticalOrigin: Cesium.VerticalOrigin.BOTTOM,
            scale: 1, // 标注点icon缩放比例
            width: 30, // 设置标注点icon的高和宽，单位默认时px
            height: 40,
            pixelOffset: new Cesium.Cartesian2(0, -40 * 1.0 * 0.5), //偏移计算公式：(-1) *height*scale*0.5,即:向上移动50%
          },
          dataId: pointObj.id,
        });
      });
      this.handlePointClick();
    },
    handlePointClick() {
      let that = this;
      that.handlerClick = new Cesium.ScreenSpaceEventHandler(
        that.viewer.scene.canvas
      );
      that.handlerClick.setInputAction(function (click) {
        console.log(click, "click");
        let pick = that.viewer.scene.pick(click.position);
        console.log(pick, "pick");
        if (pick && pick.id) {
          //点击后的操作
        }
      }, Cesium.ScreenSpaceEventType.LEFT_CLICK);
    },
    //删除地图绘制的点
    // initMapPoints(){
    //   this.viewer.entities.removeAll();  //删除地图上绘制的所有的点
    //   this.viewer.dataSources.removeAll(); //删除地图上面的聚合点
    //   if(this.handlerClick!=''){         //删除地图点的点击事件
    //     this.handlerClick.removeInputAction(Cesium.ScreenSpaceEventType.LEFT_CLICK)
    //   }
    // },
    getInit() {
      let that = this;
      var cesiumAsset =
        "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJqdGkiOiI5MDkwMThmZi0zMTRhLTRjZjctOTRhNy02M2IyMzU3NTNmMjEiLCJpZCI6MTE4ODE0LCJpYXQiOjE2NzE1MDU0NzB9.lQJTU6sYDerhrVwzWW4B5sPoPkNQyXTt8snnN4EGL8M";
      //反色滤镜invert
      var token = "83adcbbc060300d1514d62a257126eeb";
      var subdomains = ["0", "1", "2", "3", "4", "5", "6", "7"];
      // var mapOption = {
      //   url: "https://t7.tianditu.gov.cn/img_w/wmts?service=WMTS&version=1.0.0&request=GetTile&tilematrix={z}&layer=img&style=default&tilerow={y}&tilecol={x}&tilematrixset=w&format=tiles&tk=83adcbbc060300d1514d62a257126eeb",
      //   //     //地图可进行切换
      //   //     //高德影像地图
      //   //     //url:"https://webst04.is.autonavi.com/appmaptile?style=6&x={x}&y={y}&z={z}",
      //   //     //google地图（国内暂时被封），后续如果开放可直接f12-->network获取服务
      //   //     //osm矢量地图
      //   //     //url:"https://b.tile.openstreetmap.org/{z}/{x}/{y}.png",
      //   //     //mapbox影像地图(token如果过期，请选择其他地图图层)
      //   //     //url:"https://api.mapbox.com/styles/v1/marsgis/cki0adkar2b0e19mv9tpiewld/tiles/512/{z}/{x}/{y}@2x?access_token=pk.eyJ1IjoibWFyc2dpcyIsImEiOiJja2Fod2xlanIwNjJzMnhvMXBkMnNqcjVpIn0.WnxikCaN2KV_zn9tLZO77A"
      //   //     //arcgis影像地图
      //   //     url:""
      // };
      // var imgProvider = new Cesium.UrlTemplateImageryProvider(mapOption);
      Cesium.Ion.defaultAccessToken = cesiumAsset;
      this.viewer = new Cesium.Viewer("cesiumContainer", {
        homeButton: false,
        sceneModePicker: false, // 如果设置为false，将不会创建右上角投影方式控件(显示二三维切换按钮)。
        baseLayerPicker: false, // 如果设置为false，将不会创建右上角图层按钮。
        // 影像切换
        animation: false,
        // 是否显示动画控件
        infoBox: false, // 是否显示点击要素之后显示的信息
        selectionIndicator: false, // 要素选中框
        geocoder: false, // 是否显示地名查找控件
        timeline: false, // 是否显示时间线控件
        fullscreenButton: false,
        shouldAnimate: false, // 默认true ，否则为 false 。此选项优先于设置 Viewer＃clockViewModel 。
        sceneMode: 3, // 初始场景模式 1 2D模式 2 2D循环模式 3 3D模式  Cesium.SceneMode
        baselLayerPicker: false, // 将图层选择的控件关掉，才能添加其他影像数据
        shadows: false,
        navigationHelpButton: false, // 是否显示帮助信息控件
        skyAtmosphere: false,//关闭大气层
        // orderIndependentTranslucency: false,
        contextOptions: {
          webgl: {
            alpha: true,
          },
        },
      });
      // that.viewer.scene.sun.show = false;
      // that.viewer.scene.moon.show = false;
      // that.viewer.scene.skyBox.show = false; //关闭天空盒，否则会显示天空颜色
      
      // that.viewer.scene.undergroundMode = true;
      // that.viewer.scene.globe.show = true;
      // that.viewer.scene.backgroundColor = new Cesium.Color(0, 0, 0, 0);
      // that.viewer.scene.screenSpaceCameraController.minimumZoomDistance = 1000;
      // that.viewer.scene.screenSpaceCameraController.maximumZoomDistance = 5600000;
      if (Cesium.FeatureDetection.supportsImageRenderingPixelated()) {
        //判断是否支持图像渲染像素化处理
        that.viewer.resolutionScale = window.devicePixelRatio;
      }
      that.viewer.scene.fxaa = true;
      that.viewer.scene.postProcessStages.fxaa.enabled = true;

      //高德地图影像
      // var imageLyser = new Cesium.ImageryLayer(new Cesium.UrlTemplateImageryProvider({
      //   url:"http://webst01.is.autonavi.com/appmaptile?style=8&x={x}&y={y}&z={z}",
      //   minimumLevel:1,
      //   maximumLevel:18
      // }));
      // this.viewer.imageryLayers.add(imageLyser);
      // 天地图不加地名
      // var imageLyser = new window.Cesium.WebMapTileServiceImageryProvider({
      //   url:
      //     "http://t{s}.tianditu.com/img_w/wmts?service=wmts&request=GetTile&version=1.0.0&LAYER=img&tileMatrixSet=w&TileMatrix={TileMatrix}&TileRow={TileRow}&TileCol={TileCol}&style=default&format=tiles&tk=" +
      //     token,
      //   subdomains: subdomains,
      //   layer: "tdtImgLayer",
      //   style: "default",
      //   format: "image/jpeg",
      //   tileMatrixSetID: "GoogleMapsCompatible", //使用谷歌的瓦片切片方式
      //   show: true,
      // });
      // this.viewer.imageryLayers.addImageryProvider(imageLyser);
      // 天地图加地名
      // var imageLyser = new window.Cesium.WebMapTileServiceImageryProvider({
      //   //影像注记
      //   url:
      //     "http://t{s}.tianditu.com/cia_w/wmts?service=wmts&request=GetTile&version=1.0.0&LAYER=cia&tileMatrixSet=w&TileMatrix={TileMatrix}&TileRow={TileRow}&TileCol={TileCol}&style=default.jpg&tk=" +
      //     token,
      //   subdomains: subdomains,
      //   layer: "tdtCiaLayer",
      //   style: "default",
      //   format: "image/jpeg",
      //   tileMatrixSetID: "GoogleMapsCompatible",
      //   show: true,
      // });
      // this.viewer.imageryLayers.addImageryProvider(imageLyser);
      // // 叠加国界服务
      var imageLyser = new window.Cesium.UrlTemplateImageryProvider({
        url:
          "https://t{s}.tianditu.gov.cn/DataServer?T=ibo_w&x={x}&y={y}&l={z}&tk=" +
          token,
        subdomains: subdomains,
        tilingScheme: new window.Cesium.WebMercatorTilingScheme(),
        maximumLevel: 10,
      });
      this.viewer.imageryLayers.addImageryProvider(imageLyser);
      // end

      this.viewer._cesiumWidget._creditContainer.style.display = "none"; // 隐藏cesium ion
      var obj = {
        lng: 120.854717,
        lat: 30.735304,
        eyeHeight: 100000,
        pitch: -65,
        heading: 0.0,
        time: 0.1,
      };
      this.viewerFlyToLonLat(obj);
    },
    viewerFlyToLonLat(obj) {
      let that = this;
      console.log("飞行参数：", obj.lng, obj.lat, obj.eyeHeight);
      let cartographics = [Cesium.Cartographic.fromDegrees(obj.lng, obj.lat)];
      cartographics.obj = obj;
      Cesium.sampleTerrain(
        that.viewer.scene.terrainProvider,
        14,
        cartographics
      ).then((updatedPositions) => {
        var flyToHeight = updatedPositions[0].height;
        if (typeof flyToHeight == "undefined") {
          updatedPositions.obj.height = 0;
        } else {
          updatedPositions.obj.height = flyToHeight;
        }
        if (this.flyToEntity) {
          that.viewer.entities.remove(this.flyToEntity);
        }
        this.flyToEntity = new Cesium.Entity({
          id: "flyTmp",
          position: Cesium.Cartesian3.fromDegrees(
            updatedPositions.obj.lng,
            updatedPositions.obj.lat,
            updatedPositions.obj.height
          ),
          point: {
            pixelSize: 0, //控制居中的时候是否展示中心点
            color: Cesium.Color.RED.withAlpha(0.9),
            outlineColor: Cesium.Color.WHITE.withAlpha(0.9),
            outlineWidth: 0,
          },
        });
        // console.log("updatedPositions", updatedPositions);
        that.viewer.entities.add(this.flyToEntity);
        var flyPromise = that.viewer.flyTo(this.flyToEntity, {
          duration: updatedPositions.obj.time, //飞行时间,单位：秒
          offset: {
            heading: Cesium.Math.toRadians(updatedPositions.obj.heading), //旋转角度
            pitch: Cesium.Math.toRadians(updatedPositions.obj.pitch), //倾斜角度
            range: updatedPositions.obj.eyeHeight, //视角高度
          },
        });
        // 飞行完后
        flyPromise
          .then(function (fly) {
            console.log(fly, "飞行结束");
            if (fly) {
              that.addMarker();
              that.addGeojson();
            }
          })
          .catch(function (error) {
            console.log(error);
          });
      });
    },
    addGeojson() {
      let that = this;
      // 纯色背景,Cesium.Color.TRANSPARENT透明
      that.viewer.scene.globe.baseColor = Cesium.Color.TRANSPARENT;
      //viewer.scene.globe.baseColor = Cesium.Color.BLUE;
      //viewer.scene.backgroundColor = new Cesium.Color(255, 0.0, 0.0, 0.0);
      that.viewer.scene.backgroundColor = Cesium.Color.TRANSPARENT;
      //Cesium.Math.setRandomNumberSeed(0);  //设置随机数种子
      var promise = Cesium.GeoJsonDataSource.load(pinggubianjieJson); //geojson面数据
      promise.then(function (dataSource) {
        that.viewer.dataSources.add(dataSource);
        var entities = dataSource.entities.values;
        //var colorHash = {};
        console.log("entities.length", entities.length);

        for (var i = 0; i < entities.length; i++) {
          var entity = entities[i];
          var name = entity.name; //geojson里面必须得有一个name属性，entity.name对应
          // var index = parseInt(10 * Math.random());
          // var color = that.colors[index];
          // console.log("index", i, color);

          var cesiumColor = Cesium.Color.fromCssColorString("#597ef7a1");
          //Cesium.Color.fromCssColorString('#67ADDF');

          console.log("cesiumColor", cesiumColor);
          entity.polygon.material = cesiumColor;
          entity.polygon.outline = false;
          entity.polygon.extrudedHeight = 1000;
          //viewer.zoomTo(promise);
        }
      });
    },
  },
};
</script>

<style scoped lang="scss">
.cesium-container {
  width: 100%;
  height: 800px;
  background-color: black;
}
</style>
